package com.cep.client;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.TextView;

public class ServerIPWatcher implements TextWatcher {
	private static ServerIPWatcher instance = null;

	public static void init(TextView consoleOutputTV_,
			CEPAndroidClientActivity parent_) {
		instance = new ServerIPWatcher(consoleOutputTV_, parent_);
	}

	public static ServerIPWatcher instance() {
		return instance;
	}

	private String serverIP = null;
	private TextView consoleOutputTV = null;
	private CEPAndroidClientActivity parent = null;

	private ServerIPWatcher(TextView consoleOutputTV_,
			CEPAndroidClientActivity parent_) {
		this.consoleOutputTV = consoleOutputTV_;
		serverIP = "192.168.2.198";
		parent = parent_;
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		this.serverIP = arg0.toString();
		if (checkIP(serverIP) == false) {
			consoleOutputTV.setText("Invalid IP");
			parent.enableInput(false);
		} else {
			consoleOutputTV.setText("");
			parent.enableInput(true);
		}
	}

	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

	}

	public String getServerIP() {
		return serverIP;
	}

	private boolean checkIP(String IP) {
		IP = IP.trim();
		String[] parts = IP.split("\\.");
		if (parts.length != 4)
			return false;

		for (String s : parts) {
			int i = Integer.parseInt(s);
			if (i < 0 || i > 255) {
				return false;
			}
		}
		return true;
	}
}
